<?php
namespace App\Http\Middleware;

use Closure;
use App\Libs\Commons\MyMessage;
use App\Libs\Commons\MyLogger;

class ApiMiddleware
{

	/**
	 * Handle an incoming request.
	 *
	 * @author zhe.wang
	 * @param \Illuminate\Http\Request $request        	
	 * @param \Closure $next        	
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		$method = $request->method();
		MyLogger::debug('ApiMiddleware', [
			'method' => $method,
			'all' => $request->all()
		]);
		
		$env = config('app.env');
		if ($env == 'local' || $env == 'test') { // debug
			return $next($request);
		} else {
			if (strtoupper($method) != 'POST') {
				return My_error(MyMessage::REQUEST_METHOD_NEED_POST);
			}
			$apps = config('auth.apps');
			$params = $request->post();
			$appID = $params['appid'] ?? '';
			$sign = $params['sign'] ?? '';
			if (empty($appID) || empty($sign) || empty($apps[$appID])) {
				return My_error(MyMessage::SYSTEM_MIDDLEWARE_PARAM_LOSE);
			}
			$appKey = $apps[$appID];
			unset($params['sign']);
			ksort($params);
			$string = '';
			foreach ($params as $k => $v) {
				$string .= ($string ? '&' : '') . $k . '=' . rawurlencode($v);
			}
			$ckSign = strtolower(md5($string . $appKey));
			if ($sign != $ckSign) {
				MyLogger::error('ApiMiddleware 签名验证失败', [
					'sign' => $sign,
					'ckSign' => $ckSign,
					'string' => $string
				]);
				return My_error(MyMessage::SYSTEM_MIDDLEWARE_SIGN_ERROR);
			}
		}
		return $next($request);
	}
}
